import { getToken } from "@/utils/common";
import { createRouter, createWebHistory } from "vue-router";
import store from "@/store";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      name: "index",
      component: () => import("@/layout/index.vue"),
      children: [
        // {
        //   path: "",
        //   name: "home",
        //   component: () => import("@/pages/home/index.vue"),
        // },
        // {
        //   path: "/examples/test1",
        //   component: () => import("@/pages/examples/test1/index.vue"),
        // },
        // {
        //   path: "/examples/test2",
        //   component: () => import("@/pages/examples/test2/index.vue"),
        // },
        // {
        //   path: "/examples/test3",
        //   component: () => import("@/pages/examples/test3/index.vue"),
        // },
        // {
        //   path: "/sys/user",
        //   name: "sys_user",
        //   component: () => import("@/pages/sys/user/index.vue"),
        // },
        // {
        //   path: "/sys/menu",
        //   name: "sys_menu",
        //   component: () => import("@/pages/sys/menu/index.vue"),
        // },
        // {
        //   path: "/sys/role",
        //   name: "sys_role",
        //   component: () => import("@/pages/sys/role/index.vue"),
        // },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/pages/login/index.vue"),
    },
    {
      path: "/403",
      name: "403",
      component: () => import("@/pages/errors/403.vue"),
    },
    {
      // 404路由，以前是 * 号，现在换成 /:pathMatch(.*)*
      path: "/:pathMatch(.*)*",
      name: "404",
      component: () => import("@/pages/errors/404.vue"),
    },
  ],
});

// 全局前置守卫
router.beforeEach(async (to) => {
  if (to.name !== "login") {
    // 获取token
    const token = getToken();

    // 没有token，则直接打到登录页面
    if (!token) {
      return {
        name: "login",
        query: {
          redirect: to.fullPath,
        },
      };
    }

    // 获取个人信息
    if (!store.state.user.person) {
      // 获取个人信息，返回的是用户拥有权限访问的路由地址集合 ['/','/sys/menu', '/sys/role']
      //                                              [{}, {}, {}]
      const authRoutes = await store.dispatch("user/get");

      console.log("authRoutes", authRoutes);

      // 动态添加路由，使用 router.addRoute 方法
      authRoutes.forEach((item) => {
        router.addRoute("index", {
          path: item.router,
          name: item.router.substr(1).split("/").join("_"),
          // TODO. 上线后有问题，后续使用 import.meta.glob 一次导入多个模块的方式来解决
          // component: () => import(`/src/pages/${item.viewPath}`),
          component: () => import(`/src/pages/${item.router}/index.vue`),
        });
      });

      console.log("最新的routes", router.getRoutes());
      // 再次重定向
      return to.path;
    }
  }
});

export default router;
